package com.pai4j.message.provider;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.message.core.provider.AbstractResourceProvider;
import com.pai4j.message.model.ResourceInfo;
import com.pai4j.remote.ugc.MomentClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 动态资源提供者
 * 提供PAI圈动态资源信息
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
@ConditionalOnBean(MomentClient.class)
public class MomentResourceProvider extends AbstractResourceProvider {

    @Autowired
    private MomentClient momentClient;

    @Override
    public String getResourceType() {
        return "MOMENT";
    }

    @Override
    protected ResourceInfo doGetResourceInfo(String resourceId) {
        if (StringUtils.isBlank(resourceId)) {
            return null;
        }

        try {
            Long momentId = Long.parseLong(resourceId);
            PAIResponseBean<MomentVO> response = momentClient.detail(momentId);
            
            if (!PAIResponseBeanUtil.isOk(response) || response.getData() == null) {
                log.warn("获取动态信息失败: momentId={}", momentId);
                return null;
            }

            MomentVO moment = response.getData();
            
            // 构建资源信息
            ResourceInfo.ResourceInfoBuilder builder = ResourceInfo.builder()
                    .resourceId(resourceId)
                    .resourceType("MOMENT")
                    .ownerId(moment.getAuthor())
                    .authorName(moment.getAuthorInfo().getUserName())
                    .jumpUrl("/moment/detail/" + resourceId)
                    .status(null)
                    .createTime(moment.getPublishTime());

            // 设置标题（动态内容摘要）
            if (StringUtils.isNotBlank(moment.getContent())) {
                String title = moment.getContent();
                if (title.length() > 50) {
                    title = title.substring(0, 47) + "...";
                }
                builder.title(title);
                builder.summary(moment.getContent());
            }

            // 设置封面图（取第一张图片）
            if (!CollectionUtils.isEmpty(moment.getImages())) {
                String imageUrl = String.valueOf(moment.getImages().get(0));
                builder.coverImage(imageUrl);
            }

            return builder.build();

        } catch (Exception e) {
            log.error("获取动态资源信息异常: resourceId={}, error={}", resourceId, e.getMessage(), e);
            return null;
        }
    }

    @Override
    public int getPriority() {
        return 10; // 高优先级
    }
}

